<template>
  <div class="headerbox">
    <div class="header">
      <div class="headerL">
        <a onclick="javascript:history.back(-1)" class="goback"><img src="/images/goback.png" /></a>
      </div>
      <div class="headerC0">
        <div class="ssdiv">
          <img src="/images/ss.png" />
          <input name="" type="text" v-model="searchKey" @keyup.enter="searchShop" @input="handleInput"
            placeholder="输入关键字..." />
        </div>
      </div>
      <div class="headerR">
        <a href="javascript:void()"><img src="/images/tr.png" /></a>
      </div>
    </div>
  </div>
  <div class="clear"></div>
  <div class="shopType">
    <van-dropdown-menu active-color="#ee0a24" style="max-width: 521px !important;">
      <van-dropdown-item style="max-width: 512px !important;" v-model="clValue" :options="option1"
        @change="handleChange" />
      <van-dropdown-item style="max-width: 512px !important;" v-model="raValue" :options="option2"
        @change="handleRank" />
    </van-dropdown-menu>

    <!-- <ul>
      <li class="on">
        <select name="" v-model="isSelectClass" @change="handleChange">
          <option value="0" selected>全部商品</option>
          <option value="3">推荐商品</option>
          <option value="2">热销商品</option>
          <option value="1">新品商品</option>
        </select>
      </li>
      <li>
        <select name="" id="" v-model="isRank" @change="handleRank">
          <option value="0" selected>默认排序</option>
          <option value="1" selected>价格排序</option>
          <option value="2" selected>库存排序</option>
        </select>
      </li>
    </ul> -->
  </div>
  <div class="clear"></div>
  <div class="hbox"></div>
  <div class="mainWarp" style="background:#f3f3f3">
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div class="box">
          <div class="box01" v-for="item in allShopList" :key="item.id" @click="goDetail(item.id)">
            <!-- <a href="detail.html"> -->
            <img :src="item.shopUrl_text" />
            <!-- </a> -->
            <!-- <a href="detail.html"> -->
            <p class="tit">{{ item.content }}</p>
            <!-- </a> -->
            <div class="price">
              <p style="color: #e06c75; font-weight: bold;">{{ item.price }}<span
                  style="text-decoration: line-through; color: #7c7c7c;">￥{{ item.price_origin }}</span></p>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
  <div class="clear"></div>
  <div class="h54"></div>
  <div class="clear"></div>
  <van-back-top class="custom" style="background-color: rgba(255, 255, 255,0); color: #198dfb;" bottom="8vh"
    right="5vw"></van-back-top>
  <div class="footerBox">
    <Tab :modelValue="currentTab" @update:modelValue="handleTabUpdate"></Tab>
  </div>
</template>

<style scoped>
.box {
  display: flex;
  /* 启用 Flex 布局 */
  flex-wrap: wrap;
  /* 禁止换行（默认值），强制子项在一行 */
  /* 可选：控制子项间距 */
  gap: 4%;
  /* 子项间间距（替代 margin，更简洁） */
  justify-content: flex-start;
  /* 子项在容器内的水平对齐方式 */
}

/* 置顶样式 */
.custom {
  width: 80px;
  text-align: center;
}


.box01 {
  width: 48%;
  background-color: white;
  margin-bottom: 10px;
  margin-top: 1%;
  padding: 2px 2px;
}

.box01 img {
  display: flex;
  width: 100%;
  height: 192px;
}

.tit {
  font-weight: bold;
  font-size: 0.9rem;
  color: #666;
}
</style>
<script setup>
import { ref, onMounted } from 'vue';
import Tab from './comm/Tab.vue';
import { POST } from '../services/request.js';
import { showToast } from 'vant';
import { useRouter } from 'vue-router';
const router = useRouter();
const currentTab = ref('search'); // 当前选中的标签页
const handleTabUpdate = (newValue) => {
  currentTab.value = newValue; // 更新父组件的状态
};
// 刷新初始状态
const refreshing = ref(false);
// 输入框关键词
const searchKey = ref('');
// 获取全部商品
const allShopList = ref([]);
// 定义分类选的值
// const isSelectClass = ref('0');
const classData = ref('');
// 上拉刷新状态
const loading = ref(false);
const finished = ref(false);
// 定义起始页
const page = ref(1);
const count = ref('');
// 获取排序选中的值
// const isRank = ref('0');
// const rankData=ref('');
const clValue = ref(0);
const raValue = ref(0);
const option1 = [
  { text: '全部商品', value: 0 },
  { text: '新款商品', value: 1 },
  { text: '热销商品', value: 2 },
  { text: '推荐商品', value: 3 },
];
const option2 = [
  { text: '默认排序', value: 0 },
  { text: '价格排序', value: 1 },
  { text: '库存排序', value: 2 },
];



let timeoutId = null; // 用于存储防抖定时器

onMounted(async () => {
  await getClass(clValue.value, raValue.value, searchKey.value, page.value);
});

// 模拟刷新逻辑
const onRefresh = async () => {
  // if (refreshing.value) return; // 防止重复触发
  // 1.开启刷新
  page.value = 1;//重置页码
  allShopList.value = []; // 清空数据
  refreshing.value = true;
  // 这个方法就是执行这个getClass方法后，下拉刷新状态要结束刷新状态
  await getClass(clValue.value, raValue.value, searchKey.value, page.value).finally(() => {
    refreshing.value = false;  //结束刷新状态
    showToast('刷新成功');
  })

};

// 上拉刷新功能--分页
const onLoad = async () => {
  // if(lock.value){
  // if(finished.value || loading.value) return; //数据加载完成或正在加载时不请求
  page.value++;
  getClass(clValue.value, raValue.value, searchKey.value, page.value);
  // }
};

// 分类的选中处理
const handleChange = async () => {
  // 获取分类的值
  // isSelectClass.value = event.target.value;
  allShopList.value = [];
  page.value = 1;
  await getClass(clValue.value, raValue.value, searchKey.value, page.value);
};

// 排序的选中处理
const handleRank = async (event) => {
  // isRank.value = event.target.value;
  // // console.log(isRank.value);
  // await getClass(isSelectClass.value, isRank.value, searchKey.value);
  allShopList.value = [];
  page.value = 1;
  await getClass(clValue.value, raValue.value, searchKey.value, page.value);
};


// post提交到查询分类 和 排序
const getClass = async (clValue, raValue, seValue, page) => {
  // console.log(seValue);

  // 调用这个方法时，需进行加载，使用需将状态改为正再加载，也就是改为true
  loading.value = true;
  // lock.value=false
  classData.value = {
    clValue: clValue,
    raValue: raValue,
    seValue: seValue,
    page: page,
  }
  const classShopRes = await POST({
    url: '/Index/getClassShop',
    params: classData.value,
  })
  // console.log(classShopRes.code,'code');

  if (classShopRes.code === 1) {

    // console.log(classShopRes.code, 'qqq');
    // allShopList.value=[];
    allShopList.value.push(...classShopRes.data);
    // 数据push进去后，则加载完成，需将加载状态变回false状态
    loading.value = false;
    // loading.value = false; //上拉
    // count.value=(classShopRes.data).length;
    // console.log(count.value);
    // allShopList.value.push(classShopRes.data);
    if (classShopRes.data.length == 0) {
      // 如果数据等于0，则就不再显示
      finished.value = true;
    } else {
      // 但是如果下拉刷新的话，重置为1时，则需要再设置回去
      finished.value = false;
    }

  } else {
    showToast(classShopRes.code + '没有数据了');
  }
}

// 搜索功能 
const searchShop = async () => {
  allShopList.value = [];
  page.value = 1;
  await getClass(clValue.value, raValue.value, searchKey.value, page.value);
}

// 防抖处理：用户停止输入 300ms 后触发搜索
const handleInput = (e) => {
  if (timeoutId) clearTimeout(timeoutId); // 清除上一次定时器
  timeoutId = setTimeout(() => {
    searchShop();
  }, 500); // 300ms 可根据需求调整
};

// 详情页
const goDetail = async (id) => {
  // 跳转时传递参数
  await router.push({
    name: 'detail',
    params: { id }
  });
}






</script>